package com.example.filter;

import com.example.handler.RootHandler;
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SSOFilter extends Filter {

    private static final Logger log = Logger.getLogger(SSOFilter.class.getCanonicalName());

    @Override
    public void doFilter(HttpExchange httpExchange, Chain chain) throws IOException {
       log.info("====进入Filter====");
        URI uri = httpExchange.getRequestURI();
        if(uri.getPath().startsWith("/static")){
            chain.doFilter(httpExchange);
            return;
        }
        Map<String,String> parameters = getQueryString(uri.getQuery());
        if(parameters.containsKey("name")){
            HttpHandler root = new RootHandler();
            root.handle(httpExchange);
        }else {
            try {
                Headers headers = httpExchange.getRequestHeaders();
                Headers modifiableRequestHeaders = new Headers();
                modifiableRequestHeaders.putAll(headers);
                modifiableRequestHeaders.add("userId","xurongbei");
                httpExchange.setAttribute("requestHeaders",modifiableRequestHeaders);
            }catch (Exception e){
               log.log(Level.SEVERE,"组装请求头失败！",e);
            }
            chain.doFilter(httpExchange);
        }
    }

    @Override
    public String description() {
        return "welcome to china";
    }

    private Map<String,String> getQueryString(String qs){
        if(qs == null){
            return new HashMap<>();
        }
        Map<String ,String> queryMap = new HashMap<>();
        if(qs.contains("&")){
            String[] keyValueArr = qs.split("&");
            Arrays.stream(keyValueArr).forEach(keyValue -> {
                String key = keyValue.split("=")[0];
                String value = keyValue.split("=")[1];
                queryMap.put(key,value);
            });
        }else{
            String key = qs.split("=")[0];
            String value = qs.split("=")[1];
            queryMap.put(key,value);
        }
        return queryMap;
    }
}
